<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
  "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<%@ page import="java.sql.*" %>

<% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); %>
<%@taglib uri='/WEB-INF/cewolf.tld' prefix='cewolf' %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@page import="java.text.NumberFormat" %>
<%@page import="java.text.ParseException" %>


<!-- Variables from a previous form submission -->
<% String n = (request.getParameter("nUnits")==null)?"1":
     request.getParameter("nUnits");
   String start = (request.getParameter("calStartDateN")==null)?"":
     request.getParameter("calStartDateN");
   String end = (request.getParameter("calEndDateN")==null)?"":
     request.getParameter("calEndDateN");
   String dateSelection = (request.getParameter("dateS")==null)?"Weeks":
     request.getParameter("dateS").trim();
   String dateRadio = (request.getParameter("dateRadio")==null)?"date":
     request.getParameter("dateRadio");
   String sensorListArray[] = (request.getParameter("sensorList")==null)?null:
     request.getParameterValues("sensorList");
   //Cleanse number input by formatting the input string to an integer and then 
   //  converting back to a string 
   NumberFormat fmt=NumberFormat.getInstance();
   int ni = 0;
   try { ni = fmt.parse(n.trim()).intValue();
     n = Integer.toString(ni);
   }
   catch(ParseException a) {
     n="0";
     ni=0;
   }
%>

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-5">
  <TITLE>IntelliCORE - Long-Term State</TITLE>
  <link rel="stylesheet" type="text/css" media="screen" charset="utf-8" 
    href="css/common.css">
  <!-- calendar stylesheet -->
  <link rel="stylesheet" type="text/css" media="all" href="css/calendar-system.css" 
    title="system">
  <!-- main calendar program -->
  <script type="text/javascript" src="calendar/calendar.js"></script>
  <!-- language for the calendar -->
  <script type="text/javascript" src="calendar/lang/calendar-en.js"></script>
  <!-- the following script defines the Calendar.setup helper function, which 
       makes adding a calendar a matter of 1 or 2 lines of code. -->
  <script type="text/javascript" src="calendar/calendar-setup.js"></script>
  <!-- Long-Term State DHTML functions -->
  <script type="text/javascript" src="longtermstate.js"></script>
    
</head>
<body>
<%@ include file="header.jspf" %>

<h1>Long-Term State</h1>

<form action="longtermstate.jsp" method="post">
<fieldset>
<legend>Date Range</legend>
<!-- Date input fields -->
<input type="radio" id="r1" name="dateRadio" value="date" 
  onclick="dateEnableToggle('date')"<%if(dateRadio.startsWith("date")){%>
  checked="checked"<%}%>>
<label for="r1">Select the last </label>
<input type="text" name="nUnits" id="dateNUnits" size="2" 
  onclick="dateEnableToggle('date')" maxlength="4"<%if(dateRadio.startsWith("cal")){%> 
  style="background-color: #CCCCCC;"<%}%> value="<%= n%>">
<select name="dateS" id="dateSelect" onBeforeActivate="dateEnableToggle('date')" 
  onclick="dateEnableToggle('date')"<%if(dateRadio.startsWith("cal")){%> 
  style="background-color: #CCCCCC;"<%}%>>
<% String dateSelections[] = {"Years", "Months", "Weeks", "Days", "Hours"};
   for(int di=0; di<dateSelections.length; di++) { %>
     <option value="<%=dateSelections[di]%>"
     <%if(dateSelection.startsWith(dateSelections[di])){%> selected="selected"<%}%>>
     <%=dateSelections[di]%></option>
<% } %>
</select>&nbsp;&nbsp;&nbsp;or&nbsp;&nbsp;&nbsp;
<input type="radio" id="r2" name="dateRadio" value="cal" 
  onclick="dateEnableToggle('cal')" <%if(dateRadio.startsWith("cal")){%>
  checked="checked"<%}%>>
<label for="r2">from start: </label><input type="text" name="calStartDateN" 
  id="calStartDateBox" onfocus="calBlur()" <%if(dateRadio.startsWith("date")){%>
  style="background-color: #CCCCCC;" <%}%>size="15" maxlength="16" value="<%=start%>">
<label for="r2">to end: </label><input type="text" name="calEndDateN" 
  id="calEndDateBox" onfocus="calBlur()" <%if(dateRadio.startsWith("date")){%>
  style="background-color: #CCCCCC;" <%}%>size="15" maxlength="16" value="<%=end%>">
&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" name="submit" Value="Show Graph">
</fieldset>


<script type="text/javascript">
    Calendar.setup({
        inputField     :    "calStartDateBox",   // id of the input field
        ifFormat       :    "%Y/%m/%d %H:%M",       // format of the input field
        showsTime      :    true,
        timeFormat     :    "24",
        weekNumbers    :    false,
        onUpdate       :    catcalc
    });
    Calendar.setup({
        inputField     :    "calEndDateBox",
        ifFormat       :    "%Y/%m/%d %H:%M",
        showsTime      :    true,
        timeFormat     :    "24",
        weekNumbers    :    false,
        onUpdate       :    catcalc
    });
</script>
<p style="margin-left: 13px; margin-bottom: -2.5em; margin-top: 1em;">
  Available Sensors</p>
<!-- Get sensor names and groups from database and build sensor tree -->
<%  Connection conn = null;
    ResultSet result = null;
    PreparedStatement stmt = null;
    ResultSetMetaData rsmd = null;
    String group = "";
    int ci = 0;
    int cj = 0;
    int ck = 0;
    int selectedGroupsLength = 0;
    String selectedGroups[] = new String[255];

    Class c = Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost/Sensors", "root", 
                                       "demo07");

//Determine which groups have a sensor checked, expand only those groups on submit
	if(sensorListArray != null) {
		//concat sensor TIDs into ORed list
		String sensors = "(";
		for(ci=0; ci< sensorListArray.length; ci++) {
			sensors += "TID=" + sensorListArray[ci].substring(0, 
			                                  sensorListArray[ci].indexOf(","));
			if(ci < sensorListArray.length-1) {
				sensors += " OR ";
			}
		}
		sensors += ")";
		
		//select group names that have a sensor checked in them
		stmt = conn.prepareStatement("select distinct Group_Name from " + 
		        "Sensor_Descriptions where " + sensors + " order by Group_Name");
    	result = stmt.executeQuery();
    	while(result.next()) {
    		selectedGroups[ck]=result.getString(1);
    		ck++;
    	}
    	selectedGroupsLength = ck;
    	ck = 0;
    }

    stmt = conn.prepareStatement("select Sensor_Label,Group_Name,TID from " + 
      "Sensor_Descriptions order by Group_Name");
    result = stmt.executeQuery();%>
    
    <!--Output the list of sensors, remembering the state from before submit-->
    <ul class="treemenu">
  <%ci=0;
    while(result.next()) { 
      if(!group.equals(result.getString(2))) {
        group = result.getString(2);
        if(ci == 0) { //first group is special
          if(sensorListArray == null || (sensorListArray != null && 
             selectedGroups[0].startsWith(group))) { 
            //if no sensors are checked, expand first group by default to show 
            //  to new users that sensors are in an expandable tree structure
            ck++;%>
            <li class="treenodeopen">
      <%  }
          else {%>
            <li class="treenode">
      <%  }
        }
        else if(ci != 0){ //the rest of the groups%>
          </ul></li>
        <%if(sensorListArray != null && ck < selectedGroupsLength && 
             selectedGroups[ck].startsWith(group)) {
          ck++;%>
          <li class="treenodeopen">
        <%}
          else {%>
          <li class="treenode">
        <%}
        }%>	
        <a href=""><%=group%></a><ul>
    <%}%>
     <li>
     <label for="c<%=ci%>"><input type="checkbox" name="sensorList" 
       value="<%=result.getString(3)%>,<%=result.getString(1)%>" id="c<%=ci%>"
       <%if(sensorListArray != null && 
            sensorListArray[cj].endsWith(result.getString(1))) {
            if(cj < sensorListArray.length-1) { cj++; }%> checked
       <%}%>> 
       <%=result.getString(1)%></label><BR>
     </li>
 <% ci++;  
    } 
    stmt.close();
    conn.close();%>

</ul></li></ul>


<p>
<div style="overflow: hidden">
<!-- Display a blank chart if form has not been submitted -->
<%if(request.getMethod().equals("GET")) { %>
  <p style="margin-top: 10em;"><center style="margin-bottom: 28em;">
  <h3>Input the desired date range above and<BR>
    check the sensors to be included in the graph,<BR>
    then click <i>Show Graph</i>.</h3></center>
  </p>
<!--Upon form submission, read date inputs, sensor selection and render a new chart-->
<% }
else if(request.getMethod().equals("POST")) { 
  java.util.Date startDate = new java.util.Date();
  java.util.Date endDate = new java.util.Date();
    
  if(dateRadio.startsWith("date")) {
    if(dateSelection.startsWith("Years")) {
      startDate.setTime(startDate.getTime()-31449600000L*ni);
      //set to n years before current date 
    } else if(dateSelection.startsWith("Months")) {
      startDate.setTime(startDate.getTime()-2570400000L*ni);
      //set to n months before current date 
    } else if(dateSelection.startsWith("Weeks")) {
      startDate.setTime(startDate.getTime()-604800000L*ni);
      //set to n weeks before current date 
    } else if(dateSelection.startsWith("Days")) {
      startDate.setTime(startDate.getTime()-86400000L*ni);
      //set to n days before current date 
    } else if(dateSelection.startsWith("Hours")) {
      startDate.setTime(startDate.getTime()-3600000L*ni);
      //set to n hours before current date 
    }
  } 
  else { //cal
    if(start != "") {
       startDate = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(start);
    }
    if(end != "") {
      endDate = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(end);
    }
  } %>
  <jsp:useBean id="plotData" class="edu.colorado.karl.databases.ChartDataProducer"/>
  <jsp:useBean id="graph" class="edu.colorado.karl.databases.ChartAxiesSetter" 
    scope="page"/>
  <jsp:setProperty name="plotData" property="startDate" value="<%=startDate%>"/>
  <jsp:setProperty name="plotData" property="endDate" value="<%=endDate%>"/> 
  <jsp:setProperty name="plotData" property="sensorList"/>
<% 
   if(plotData.getErrorMessage() == "") { //if no error %>
     <cewolf:chart id="timeChart" title="Sensor Data" type="timeseries" 
       xaxislabel="Time" yaxislabel="Sensor Temp F">
       <cewolf:colorpaint color="#FFFFFF"/>
       <cewolf:data>
         <cewolf:producer id="plotData"/>
       </cewolf:data>
       <cewolf:chartpostprocessor id="graph">
         <cewolf:param name="startDate" value="<%=startDate%>"/>
         <cewolf:param name="endDate" value="<%=endDate%>"/>
       </cewolf:chartpostprocessor>
     </cewolf:chart>
     <cewolf:img chartid="timeChart" renderer="/cewolf" width="700" height="550" 
       style="display:inline; float: left"/>
<% }
   else {%>
     <p style="margin-top: 10em;"><center style="margin-bottom: 32em;">
     <h3><%=plotData.getErrorMessage()%></h3></center></p>  
<% }
} %>
</div>
<div style="vertical-align: bottom;">
<input type="submit" name="submit" Value="Show Graph">
</div>
</form>

<%@ include file="footer.jspf" %>
